<template>
  <SectionContainer class="u-p20">
    <Tabs class="u-mb20">
      <TabsItem is-active>广告计划</TabsItem>
      <TabsItem @click="$router.push({
        name: 'generalize-cell'
      })">广告单元</TabsItem>
      <TabsItem @click="$router.push({
        name: 'generalize-creative'
      })">广告创意</TabsItem>
    </Tabs>

    <!-- 筛选 -->
    <el-form
      inline
      class="m-filter"
    >
      <el-form-item>
        <el-select
          filterable
          size="small"
          class="u-w145"
          v-model="filter.status"
          placeholder="请选择状态"
        >
          <el-option
            :value="0"
            label="全部状态"
          ></el-option>
          <el-option
            :value="2"
            label="启用"
          ></el-option>
          <el-option
            :value="1"
            label="停用"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          :clearable="false"
          size="small"
          v-model="filter.daterange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          class="u-w300"
          :picker-options="DATERANGE_OPTIONS"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="filter.keyword"
          size="small"
          placeholder="请输入广告计划名称或ID"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="search"
        >查询</el-button>
      </el-form-item>
    </el-form>

    <!-- Table -->
    <TableFull
      :data="tableData"
      :column-data="tableColumn"
      :attach-width="200"
      :total="tableTotal"
      :current-page="page.pageNo"
      @current-change="currentChange"
      @size-change="sizeChange"
      @selection-change="tableSelectionChange"
    >
      <el-form
        inline
        class="m-filter"
        slot="handle"
      >
        <el-form-item v-permission="['promote_plan_add']">
          <el-button
            type="primary"
            size="small"
            @click="operationAction('create')"
          >创建广告计划</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_plan_enable']">
          <el-button
            size="small"
            @click="openStatusMulti"
          >启用</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_plan_enable']">
          <el-button
            size="small"
            @click="closeStatusMulti"
          >停用</el-button>
        </el-form-item>
        <el-form-item>
          <CustomTableColumn :module="1" :columns.sync="tableColumn" />
        </el-form-item>
      </el-form>
      <template slot="column">
        <el-table-column
          :resizable="false"
          align="center"
          width="40"
          type="selection"
        >
        </el-table-column>
        <el-table-column
          :resizable="false"
          align="center"
          label="操作"
        >
          <el-table-column
            :resizable="false"
            align="center"
            label="总计"
            width="160"
            class-name="u-table--total"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-permission="['promote_plan_view']"
                effect="dark"
                placement="top"
                content="查看"
              >
                <i
                  @click="operationAction('detail', scope.row)"
                  class="u-table-handle iconfont iconfont-6"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_plan_edit']"
                effect="dark"
                placement="top"
                content="编辑"
              >
                <i
                  @click="operationAction('edit', scope.row)"
                  class="u-table-handle iconfont iconfont-5"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_plan_delete']"
                effect="dark"
                placement="top"
                content="删除"
              >
                <i
                  @click="openRemoveItemData(scope.row.planId)"
                  class="u-table-handle el-icon-circle-close"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_plan_copy']"
                effect="dark"
                placement="top"
                content="复制广告计划"
              >
                <i
                  @click="operationAction('copy', scope.row)"
                  class="u-table-handle iconfont iconfont-7"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_plan_addUnit']"
                effect="dark"
                placement="top"
                content="添加广告单元"
              >
                <i
                  @click="$router.push({
                    name: 'generalize-cell-detail',
                    query: {
                      action: 'create',
                      referrer: 'generalize-plan',
                      planId: scope.row.planId
                    }
                  })"
                  class="u-table-handle iconfont iconfont-34"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table-column>
        <!-- eslint-disable -->
        <el-table-column
          :resizable="false"
          align="center"
          v-for="(item, index) in tableColumn"
          v-if="item.visible"
          :key="index"
          :label="item.label"
          :sortable="item.sortable"
          :sort-by="item.prop"
        >
          <el-table-column
            :resizable="false"
            align="center"
            :label="getTableDataSumValue(item.prop, {rate: ['clickRate']})"
            :prop="item.prop"
            :width="item.width"
            class-name="u-table--total"
          >
            <template slot-scope="scope">
              <!-- 名称 -->
              <span
                class="u-tl u-link"
                v-if="item.prop === 'planName'"
                @click="$router.push({
                  name: 'generalize-cell',
                  query: {
                    planId: scope.row.planId
                  }
                })"
              >{{scope.row.planName}}</span>

              <!-- 开关 -->
              <template v-else-if="item.prop === 'switch'">
                <el-switch
                  v-if="[1, 2].indexOf(scope.row.status) !== -1"
                  @change="openStatus([scope.row.planId], scope.row.status === 1 ? 2 : 1)"
                  :value="scope.row.status"
                  :active-value="2"
                  :inactive-value="1"
                ></el-switch>
              </template>

              <!-- 点击率 -->
              <template v-else-if="item.prop === 'clickRate' && scope.row[item.prop] !== null">{{decimalMultiply(scope.row[item.prop], 100) + '%'}}</template>

              <!-- 每日预算 -->
              <template v-else-if="item.prop === 'budget'">{{scope.row.budget === 0 ? "-" : scope.row.budget}}</template>

              <!-- 推广目的 -->
              <template v-else-if="item.prop === 'adPurpose'">{{mapValue(GENERALIZE_PURPOSE, scope.row.adPurpose)}}</template>

              <!-- 状态 -->
              <template v-else-if="item.prop === 'auditStatus'">
                <span :class="{ 'u-status--progress': scope.row.promotionStatus.status === '投放中' }">{{scope.row.promotionStatus.status}}</span>
              </template>

              <!-- 竞价成功率 -->
              <template v-else-if="item.prop === 'bidsSuccessRate' && scope.row.bidsSuccessRate !== null">
                <el-tooltip
                  effect="dark"
                  placement="top"
                >
                  <div
                    slot="content"
                    class="u-w200"
                  >{{getBidsSuccessRateTooltip(scope.row.bidsSuccessRate)}}</div>
                  <span :class="{
                    'c-hint-error': scope.row.bidsSuccessRate < 0.3,
                    'c-hint-warn': scope.row.bidsSuccessRate >= 0.3 && scope.row.bidsSuccessRate <= 0.5
                  }">
                    {{decimalMultiply(scope.row.bidsSuccessRate, 100) + '%'}}
                  </span>
                </el-tooltip>
              </template>

              <!-- 其他 -->
              <template v-else>{{scope.row[item.prop]}}</template>
            </template>
          </el-table-column>
        </el-table-column>
      </template>
    </TableFull>

    <!--启用-->
    <DialogConfirm
      :visible.sync="statusOpenVisible"
      :buttons="['启 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusOpen"
      :content="`是否要启用这${statusKeys.length}个计划？`"
    ></DialogConfirm>

    <!--停用-->
    <DialogConfirm
      :visible.sync="statusCloseVisible"
      :buttons="['停 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusClose"
      :content="`是否要停用这${statusKeys.length}个计划？`"
      tip="如果计划下有正在投放的广告，停用后立刻终止广告投放！"
    ></DialogConfirm>

    <!--启用/超出预算-->
    <DialogConfirm
      :visible.sync="budgetOpenVisible"
      :buttons="['关 闭']"
      @confirm="budgetOpenVisible = false"
      content="N个计划已到达每日预算，无法手动启用，请调整计划每日预算！"
    ></DialogConfirm>

    <!--删除-->
    <DialogConfirm
      :visible.sync="removeDialogVisible"
      :buttons="['删 除', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmRemoveItemData"
      content="是否删除此计划？"
      tip="此计划关联的全部广告单元、创意将被删除，数据报表中已投放数据将正常统计！"
    ></DialogConfirm>

    <!-- 创建/编辑广告计划 -->
    <Dialog
      :visible.sync="planItemVisible"
      :title="planItemTitle"
      :width="540"
    >
      <el-form
        :model="planFormData"
        :rules="planFormRules"
        ref="planItemForm"
        class="u-pl20 u-pr20 u-pt20"
        label-width="120px"
      >
        <!--广告计划-->
        <el-form-item
          prop="planName"
          label="计划名称"
        >
          <el-input
            :disabled="['detail'].indexOf(pageAction) !== -1"
            class="u-w320"
            placeholder="名称不可重复、不可包含特殊字符"
            v-model="planFormData.planName"
          >
          </el-input>
          <ShowWordLimit
            :value="planFormData.planName"
            :maxlength="50"
          ></ShowWordLimit>
        </el-form-item>
        <!--推广目的-->
        <el-form-item
          prop="adPurpose"
          label="推广目的"
        >
          <el-select
            :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
            filterable
            placeholder="请选择"
            class="u-w320"
            v-model="planFormData.adPurpose"
          >
            <el-option
              v-for="item in GENERALIZE_PURPOSE"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-row
        class="u-pb20"
        type="flex"
        justify="center"
      >
        <el-button
          v-if="['create', 'copy'].indexOf(pageAction) !== -1"
          @click="performAction('create')"
          type="primary"
          size="small"
        >创建广告单元</el-button>
        <el-button
          v-if="['create', 'edit', 'copy'].indexOf(pageAction) !== -1"
          type="primary"
          size="small"
          @click="performAction('save')"
          :class="{'u-ml20': ['create', 'edit', 'copy'].indexOf(pageAction) !== -1}"
        >保存</el-button>
      </el-row>
    </Dialog>
  </SectionContainer>
</template>

<script>
import Moment from "moment";
import { mapActions } from "vuex";

import Dialog from "@/components/dialog";
import DialogConfirm from "@/components/dialog-confirm";
import TableFull from "@/components/table-full";
import SectionContainer from "@/components/section-container";
import Tabs from "@/components/tabs";
import TabsItem from "@/components/tabs-item";
import ShowWordLimit from "@/components/show-word-limit";
import CustomTableColumn from "@/components/custom-table-column";

import { GENERALIZE_PURPOSE } from "@/assets/js/common-option";
import DATERANGE_OPTIONS from "@/assets/js/daterange-option";
import { sessionStorage, getStrLen, mapValue, hasPermission } from "@/utils";

import { decimalMultiply } from "@/utils/decimal";
import {
  fetchPlanList,
  fetchPlanStatus,
  fetchPlanRemove,
  fetchPlanAdd,
  fetchPlanUpdate
} from "@/api";

export default {
  components: {
    Dialog,
    DialogConfirm,
    TableFull,
    SectionContainer,
    Tabs,
    TabsItem,
    ShowWordLimit,
    CustomTableColumn
  },
  data() {
    return {
      GENERALIZE_PURPOSE,
      DATERANGE_OPTIONS,

      user: sessionStorage.get("USER"),

      // 广告计划/Table
      tableData: [],
      tableColumn: [
        {
          label: "是否启用",
          prop: "switch",
          width: 55,
          visible: hasPermission(["promote_plan_enable"])
        },
        {
          label: "计划名称",
          prop: "planName",
          width: 150,
          visible: true
        },
        {
          label: "计划ID",
          prop: "planId",
          visible: true
        },
        // {
        //   label: "每日预算(元)",
        //   prop: "budget",
        //   visible: true
        // },
        {
          label: "推广目的",
          prop: "adPurpose",
          visible: true
        },
        {
          label: "状态",
          prop: "auditStatus",
          visible: true
        },
        {
          label: "竞价成功率",
          prop: "bidsSuccessRate",
          sortable: true,
          visible: true
        },
        {
          label: "APP开始下载数",
          prop: "downloadStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP下载完成数",
          prop: "downloadCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP开始安装数",
          prop: "installationStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP安装完成数",
          prop: "installationCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP激活数",
          prop: "activationNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP注册数",
          prop: "registeredNumber",
          visible: false,
          custom: true
        },
        {
          label: "总消耗(元)",
          prop: "biddingPrice",
          sortable: true,
          visible: true
        },
        {
          label: "曝光数",
          prop: "displayNumber",
          sortable: true,
          visible: true
        },
        {
          label: "点击数",
          prop: "clickNumber",
          sortable: true,
          visible: true
        },
        {
          label: "点击率",
          prop: "clickRate",
          sortable: true,
          visible: true
        },
        {
          label: "点击均价(元)",
          prop: "cpcAveragePrice",
          sortable: true,
          visible: true
        },
        {
          label: "千次曝光均价(元)",
          prop: "cpmAveragePrice",
          sortable: true,
          visible: true
        }
      ],
      tableSelectionData: [],
      tableTotal: 0,

      filter: {
        status: 0,
        daterange: [
          Moment().format("YYYY-MM-DD"),
          Moment().format("YYYY-MM-DD")
        ],
        keyword: ""
      },

      page: {
        pageSize: 50,
        pageNo: 1
      },

      // 确认弹窗
      statusOpenVisible: false,
      statusCloseVisible: false,
      statusKeys: [],
      budgetOpenVisible: false,
      removeDialogVisible: false,
      removeDialogId: "",

      // 新增/编辑广告计划
      planItemVisible: false,
      pageAction: "create",
      planItemTitle: "",
      planFormData: {},
      planFormRules: {
        // 计划名称
        planName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入广告计划"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("输入内容不能超过50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        // 推广目的
        adPurpose: {
          required: true,
          message: "请选择推广目的",
          trigger: ["blur", "change"]
        }
        // 每日预算
        // budget: {
        //   required: true,
        //   validator: (rule, value, callback) => {
        //     // 限制预算才验证预算
        //     if (this.planFormData.whetherBudget === 0) {
        //       if (!value || String(value).trim() === "") {
        //         callback(new Error("请输入每日预算"));
        //       } else if (value < 0.01 || isNaN(value)) {
        //         callback(new Error("最低0.01"));
        //       } else if (
        //         String(value).length > String(Number(value).toFixed(2)).length
        //       ) {
        //         callback(new Error("请保留2位小数"));
        //       } else {
        //         callback();
        //       }
        //     } else {
        //       callback();
        //     }
        //   },
        //   trigger: ["blur", "change"]
        // }
      }
    };
  },
  computed: {
    // 拼接选中的数据
    checkedTableData() {
      return this.tableSelectionData.map(item => item.planId);
    }
  },
  methods: {
    ...mapActions(["GeneralizeNav/UPDATE_DATA"]),
    decimalMultiply,
    mapValue,

    // 新建、编辑、复制
    operationAction(type, row = {}) {
      this.pageAction = type;
      this.planItemVisible = true;
      this.planItemTitle = `${
        { create: "创建", edit: "编辑", copy: "复制", detail: "查看" }[type]
      }广告计划`;
      // 新建默认
      if ("create" === type) {
        this.planFormData = {
          userId: this.user.userId,
          adPurpose: 0,
          budget: "",
          planName: "",
          whetherBudget: 1
        };
      } else {
        // 编辑和复制需要请求已有数据
        this.planFormData = {
          userId: this.user.userId,
          adPurpose: row.adPurpose,
          budget: row.budget || "",
          planName: row.planName,
          whetherBudget: row.whetherBudget,
          status: row.status
        };
        // 编辑的时候多带个id
        if (type === "edit") {
          this.planFormData.id = row.planId;
        }
      }
    },
    // 新建、保存、复制
    performAction(type) {
      // 新建
      if ("create" === type) {
        this.addItemJump();
      }
      // 保存
      else if ("save" === type) {
        if ("edit" === this.pageAction) {
          this.updateItemSave();
        } else {
          // 新建、复制
          this.addItemSave();
        }
      }
    },
    // 广告计划-新建
    addItem() {
      // eslint-disable-next-line
      let { budget, id, ...params } = this.planFormData;
      return fetchPlanAdd({
        query: {
          userId: this.user.userId
        },
        body:
          this.planFormData.whetherBudget === 1
            ? params
            : Object.assign(params, { budget })
      }).then(res => {
        this.planItemVisible = false;
        this["GeneralizeNav/UPDATE_DATA"]();
        this.getTable();
        return res;
      });
    },
    // 广告计划-新建保存
    addItemSave() {
      this.$refs["planItemForm"].validate(valid => {
        if (valid) {
          this.addItem();
        }
      });
    },
    // 广告计划-新建后跳转
    addItemJump() {
      this.$refs["planItemForm"].validate(valid => {
        if (valid) {
          this.addItem().then(res => {
            let { planId } = res.data;
            this.$router.push({
              name: "generalize-cell-detail",
              query: {
                action: "create",
                referrer: "generalize-plan",
                planId
              }
            });
          });
        }
      });
    },
    // 广告计划-更新
    updateItem() {
      // eslint-disable-next-line
      let { budget, ...params } = this.planFormData;
      return fetchPlanUpdate({
        body: this.planFormData.whetherBudget === 1 ? params : this.planFormData
      }).then(() => {
        this.planItemVisible = false;
        this["GeneralizeNav/UPDATE_DATA"]();
        this.getTable();
      });
    },
    // 广告计划-更新保存
    updateItemSave() {
      this.$refs["planItemForm"].validate(valid => {
        if (valid) {
          this.updateItem();
        }
      });
    },
    // 广告计划-更新后跳转
    updateItemJump() {
      this.$refs["planItemForm"].validate(valid => {
        if (valid) {
          this.updateItem().then(() => {
            this.$router.push({
              name: "generalize-cell-detail",
              query: {
                action: "create",
                referrer: "generalize-plan",
                planId: this.planFormData.planId
              }
            });
          });
        }
      });
    },
    // 重置
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 广告计划列表
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      fetchPlanList({
        query: {
          userId: this.user.userId
        },
        body: {
          ...this.page,
          startTime: this.filter.daterange[0],
          endTime: this.filter.daterange[1],
          searchNameOrId: this.filter.keyword,
          status: this.filter.status
        }
      }).then(res => {
        this.tableTotal = res.data.count;
        if (res.data.list && res.data.list.length) {
          this.tableData = this.modTableDataSumList(
            res.data.sumList,
            res.data.list
          );
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return decimalMultiply(value, 100) + "%";
        }
        return String(value);
      }
      return "";
    },
    // 表格多选
    tableSelectionChange(val) {
      this.tableSelectionData = val;
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    },
    // 确认启用
    confirmStatusOpen(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 2).then(() => {
          this.statusOpenVisible = false;
          this.getTable();
        });
      } else {
        this.statusOpenVisible = false;
      }
    },
    // 确认停用
    confirmStatusClose(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 1).then(() => {
          this.statusCloseVisible = false;
          this.getTable();
        });
      } else {
        this.statusCloseVisible = false;
      }
    },
    // 启用多个
    openStatusMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择计划",
          duration: 2000
        });
      }
      this.openStatus(this.checkedTableData, 2);
    },
    // 停用多个
    closeStatusMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择计划",
          duration: 2000
        });
      }
      this.openStatus(this.checkedTableData, 1);
    },
    // 切换状态
    openStatus(keys, value) {
      this.statusKeys = keys;
      if (1 === value) {
        this.statusCloseVisible = true;
      } else if (2 === value) {
        this.statusOpenVisible = true;
      }
    },
    // 状态操作
    changeStatus(keys, value) {
      return fetchPlanStatus({
        query: {
          ids: keys.join(),
          status: value
        }
      }).then(() => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
      });
    },
    // 删除一条广告计划
    openRemoveItemData(id) {
      this.removeDialogVisible = true;
      this.removeDialogId = id;
    },
    // 确认删除一条广告计划
    confirmRemoveItemData(index) {
      if (index === 0) {
        fetchPlanRemove({
          query: {
            id: this.removeDialogId
          }
        }).then(() => {
          this.removeDialogVisible = false;
          this["GeneralizeNav/UPDATE_DATA"]();
          this.getTable();
        });
      } else {
        this.removeDialogVisible = false;
      }
    },
    // 竞价成功率提示
    getBidsSuccessRateTooltip(rate) {
      if (rate < 0.3) {
        return "广告竞争力很低，建议提高出价以获得更多的曝光";
      } else if (rate > 0.5) {
        return "广告竞争力正常，可持续投放";
      }
      return "广告竞争力较低，建议尝试放宽定向、提高出价等方式优化";
    }
  },
  created() {
    this.getTable();
  }
};
</script>